package com.lq.springcloud.controller;


import com.lq.springcloud.entities.CommResult;
import com.lq.springcloud.entities.Payment;
import com.lq.springcloud.lb.LoadBalancer;
import com.lq.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommResult create(@RequestBody Payment payment){
        int result=paymentService.create(payment);
        log.info("***********打印输出结果"+result);
        if(result>0){
            return new CommResult(200,"插入数据库成功,serverport"+serverPort,result);
        }else{
            return new CommResult<>(444,"插入数据库失败",null);
        }
    }
    @GetMapping(value="/payment/get/{id}")
    public CommResult getPaymentById(@PathVariable("id") Long id){
        Payment payment=paymentService.getPaymentById(id);
        log.info("***********打印输出结果"+payment);
        if(payment!=null){
            return new CommResult(200,"查询数据库成功,serverport"+serverPort,payment);
        }else{
            return new CommResult<Payment>(444,"查询数据库失败",null);
        }
    }
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String elment: services) {
            log.info(elment);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getScheme()+"\t"+instance.getHost()+"\t"+instance.getUri()+
                    "\t"+instance.getInstanceId() +"\t"+instance.getPort()+"\t"+instance.getMetadata());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping(value = "/payment/timeout")
    public String paymentFeginTimeOut() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

}
